package org.nf.trading.service.app.circle.mq;


import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.nf.trading.config.RabbitConfig;
import org.nf.trading.dao.LikeMapper;
import org.nf.trading.dao.PostMapper;
import org.nf.trading.dto.LikeDTO;
import org.nf.trading.entity.Like;
import org.nf.trading.entity.Post;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author wangl
 * @date 2023/12/7
 */
@Service
@RabbitListener(queues = RabbitConfig.DIRECT_QUEUE_NAME)
@RequiredArgsConstructor
@Slf4j
public class LikeSyncConsumer {

    private final LikeMapper likeMapper;

    private final PostMapper postMapper;

    /**
     * 将点赞信息更新到数据库
     * @param dto 点赞信息
     */
    @RabbitHandler
    @Transactional
    public void receive(LikeDTO dto) {
        //更新点赞表
        if(dto.getLikeStatus()) {
            Like like = new Like();
            BeanUtils.copyProperties(dto, like);
            likeMapper.save(like);
        }else{
            likeMapper.delete(dto.getPostId(), dto.getUserId());
        }
        //更新帖子的点赞总数
        Post post = new Post();
//        BeanUtils.copyProperties(dto, post);
        post.setPostLikes(dto.getLikeCount()+"");
        post.setPostId(dto.getPostId());
        System.out.println("post的值是 = "+ post);
        postMapper.updatePostLike(post);
    }
}